package com.neuedu.ud;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * http://127.0.0.1:8080/fileupload/download?fileName=f120e71c2c214015a7177193ceaeeb80.png
 */
@WebServlet(value = "/download")
public class DownloadController extends HttpServlet{

    public static final String  baseDir = "D:\\upload";


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //收文件的id
        // String fileName = "f120e71c2c214015a7177193ceaeeb80.png";
        String fileName = req.getParameter("fileName");
        File file = new File(baseDir , fileName);
        FileInputStream fis = new FileInputStream(file);


        //设置浏览器Header

        resp.setContentType("application/octet-stream");
        resp.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
        resp.addHeader("Content-Length", "" + file.length());

        ServletOutputStream os = resp.getOutputStream();


        byte[] buffer = new byte[1024];
        int len = -1;
        while(  (len = fis.read(buffer) ) != -1){
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        fis.close();


    }
}
